<template>
    <base-page class="base-form" title="评分" @back="onCancel()">
        <view class="main-box" style="padding: 0rpx 32rpx">
            <view class="example">
                <uni-forms ref="valiForm" :rules="rules" :modelValue="currentItem" label-width="120px">
                    <uni-forms-item label="评分" required name="teacherScore">
                        <uni-easyinput v-model="currentItem.teacherScore" />
                    </uni-forms-item>
                    <uni-forms-item label="论述题目" required name="title">
                        <textarea v-model="currentItem.title" maxlength="10000"
                            style="width:100% !important;min-height:200px !important;font-size: 14px !important;"
                            class="textarea" type="textarea" disabled />
                    </uni-forms-item>
                    <uni-forms-item label="学员答案" required name="userAnswer">
                        <textarea v-model="currentItem.userAnswer" maxlength="10000"
                            style="width:100% !important;min-height:300px !important;font-size: 14px !important;"
                            class="textarea" type="textarea" disabled />
                    </uni-forms-item>
                </uni-forms>
                <view class="page-info" v-if="totalItems > 1">
                    第 {{ currentIndex + 1 }}/{{ totalItems }} 题
                </view>
                <view class="button-group">
                    <!-- 上一题按钮：只在不是第一题时显示 -->
                    <button type="default" @click="prevItem" v-if="currentIndex > 0">上一题</button>
                    <!-- 保存并下一题按钮：只在不是最后一题时显示 -->
                    <button type="default" @click="saveCurrentScore" v-if="currentIndex < totalItems - 1">保存并下一题</button>
                    <!-- 提交按钮：始终显示 -->
                    <button type="primary" @click="submitFinal">提交所有评分</button>
                </view>
                <u-toast ref="uToast" />
            </view>
        </view>
    </base-page>
</template>

<script>
import { CourseInfoController } from "@/api";

export default {
    data() {
        return {
            historyId: null,
            openSubmit: true,
            // 校验表单数据
            valiFormData: {},
            // 所有待评分项列表
            allItems: [],
            // 当前评分项
            currentItem: {},
            // 当前评分索引
            currentIndex: 0,
            // 总评分项数量
            totalItems: 0,
            // 已完成的评分列表
            questionScore: [],
            // 校验规则
            rules: {
                teacherScore: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '评分不能为空'
                        },
                        {
                            validator: (rule, value, callback) => {
                                const score = Number(value);
                                // 检查是否为数字
                                if (isNaN(score)) {
                                    callback('请输入有效数字');
                                    return;
                                }
                                // 检查是否在有效范围内
                                if (score < 0 || score > this.currentItem.systemScore) {
                                    callback(`评分必须在0-${this.currentItem.systemScore}之间`);
                                    return;
                                }
                                callback();
                            }
                        }
                    ]
                }
            }
        };
    },
    methods: {
        onCancel() {
            uni.navigateBack();
        },
        showToast() {
            this.$refs.uToast.show({
                title: '操作成功',
                type: 'success',
            })

            setTimeout(() => {
                uni.navigateBack({
                    delta: 1
                });
            }, 2000)
        },
        showErro() {
            this.$refs.uToast.show({
                title: '操作失败',
                type: 'error',
            })
        },
        // 切换到上一题
        prevItem() {
            // 先保存当前评分
            const scoredItem = {
                historyQuestionId: this.currentItem.historyQuestionId,
                teacherScore: this.currentItem.teacherScore
            };
            
            // 检查是否已存在该题的评分，如果存在则更新
            const existingIndex = this.questionScore.findIndex(
                item => item.historyQuestionId === scoredItem.historyQuestionId
            );
            
            if (existingIndex >= 0) {
                this.questionScore[existingIndex] = scoredItem;
            } else if (scoredItem.teacherScore) {
                // 只有当有评分时才添加
                this.questionScore.push(scoredItem);
            }
            
            // 切换到上一题
            if (this.currentIndex > 0) {
                this.currentIndex--;
                this.loadCurrentItem();
            }
        },
        // 保存当前评分并进入下一题
        saveCurrentScore() {
            this.$refs.valiForm.validate().then(res => {
                if (res) {
                    // 保存当前评分
                    const scoredItem = {
                        historyQuestionId: this.currentItem.historyQuestionId,
                        teacherScore: this.currentItem.teacherScore
                    };
                    
                    // 检查是否已存在该题的评分，如果存在则更新
                    const existingIndex = this.questionScore.findIndex(
                        item => item.historyQuestionId === scoredItem.historyQuestionId
                    );
                    
                    if (existingIndex >= 0) {
                        this.questionScore[existingIndex] = scoredItem;
                    } else {
                        this.questionScore.push(scoredItem);
                    }
                    
                    // 进入下一题
                    if (this.currentIndex < this.totalItems - 1) {
                        this.currentIndex++;
                        this.loadCurrentItem();
                    }
                }
            });
        },
        // 提交所有评分
        submitFinal() {
            // 先保存当前评分
            this.$refs.valiForm.validate().then(res => {
                if (res) {
                    // 保存当前评分
                    const scoredItem = {
                        historyQuestionId: this.currentItem.historyQuestionId,
                        teacherScore: this.currentItem.teacherScore
                    };
                    
                    // 检查是否已存在该题的评分，如果存在则更新
                    const existingIndex = this.questionScore.findIndex(
                        item => item.historyQuestionId === scoredItem.historyQuestionId
                    );
                    
                    if (existingIndex >= 0) {
                        this.questionScore[existingIndex] = scoredItem;
                    } else {
                        this.questionScore.push(scoredItem);
                    }
                    
                    // 提交所有评分
                    this.openSubmit = false;
                    let obj = {
                        historyId: this.historyId,
                        questionScore: this.questionScore
                    };
                    
                    console.log(obj);
                    
                    CourseInfoController.submitScore(this, obj).then((res) => {
                        console.log(res);
                        if (res) {
                            uni.showToast({
                                title: "评分提交成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                uni.navigateTo({
                                    url: `/views/generated/rating`
                                });
                            }, 1500);
                        } else {
                            this.showErro();
                        }
                    });
                }
            });
        },
        // 加载当前评分项
        loadCurrentItem() {
            
            if (this.allItems && this.allItems[this.currentIndex]) {
                // 深拷贝，避免直接修改原数据
                this.currentItem = JSON.parse(JSON.stringify(this.allItems[this.currentIndex]));
                // 检查是否已有评分
                if (this.currentItem.teacherScore == 0) {
                    this.currentItem.teacherScore = '';
                }
            }
        }
    },
    onLoad(data) {
        if (data.historyId) {
            this.historyId = JSON.parse(decodeURIComponent(data.historyId))
        }
        const obj = {
            hisId: this.historyId
        }
        CourseInfoController.getNotScorePaperDetail(this, obj).then((res) => {
            console.log(res);
            if (Array.isArray(res) && res.length > 0) {
                this.allItems = res;
                this.totalItems = res.length;
                this.currentIndex = 0;
                this.loadCurrentItem();
            }
        })
    }
}
</script>

<style lang="scss" scoped>
.textarea {
    display: flex;
    box-sizing: border-box;
    flex-direction: row;
    align-items: center;
    border: 1px solid #dcdfe6;
}

.example {
    padding: 15px;
    background-color: #fff;
}

.button-group {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.page-info {
    text-align: center;
    margin: 15px 0;
    color: #666;
    font-size: 14px;
}
</style>